package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.beans.BGsetAll;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.PrefsUtils;
import com.yuyh.library.utils.toast.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 隐私设置
 */
public class PrivacyActivity extends BaseSwipeBackActivity implements CompoundButton.OnCheckedChangeListener {

    private static final String TAG = PrivacyActivity.class.getSimpleName();
    private static final int UPDATE_PRIVATE_SET = 1000;

    private static final int SDK_PERMISSION_REQUEST = 127;
    public final  static  int CHOSE_IMG = 101 ;
    private String choesimgpath;

    @BindView(R.id.is_notification)
    Switch isNotifaction;
    @BindView(R.id.is_verify)
    Switch isVerify;
    @BindView(R.id.is_find_by_phone)
    Switch isFindByPhone;

    @BindView(R.id.alter_psd)
    LinearLayout alterPSD;
    @BindView(R.id.alter_pay_psd)
    LinearLayout alterPayPSD;
    @BindView(R.id.black_list)
    LinearLayout blackList;
    @BindView(R.id.chat_bg)
    LinearLayout chat_bg;

    @BindView(R.id.exit)
    Button exit;
    @BindView(R.id.pre_v_back)
    ImageView backImg;

    @BindView(R.id.tx_privacy_content_id)
    TextView tx_privacy_content;
    String value;
    String needAuth;
    String newNotification;
    String searchMobile;
    String userId;

    PGService mPgService;

    @Override
    public int getContentViewId() {
        return R.layout.activity_privacy;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.privacy_set);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        mPgService = PGService.getInstance();

        //这里应该获取隐私设置，更新UI
        updateUI();
    }

    @OnClick({R.id.alter_pay_psd, R.id.alter_psd, R.id.black_list, R.id.exit, R.id.chat_bg,R.id.tx_privacy_content_id})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
//            case R.id.alter_psd:
//                intent = new Intent(this, NewPasswordActivity.class);
//                intent.putExtra("type", getResources().getString(R.string.alter_psd));
//                startActivity(intent);
//                break;
//            case R.id.alter_pay_psd:
//                intent = new Intent(this, NewPasswordActivity.class);
//                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
//                startActivity(intent);
//                break;
            case R.id.black_list://黑名单
                startActivity(BlackFriendActivity.class);
                break;
            case R.id.exit:
                doExit();
                break;
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.chat_bg:
                MyDialog.showBGDialog(PrivacyActivity.this, handler);
                break;
            case R.id.tx_privacy_content_id:
                MyWebViewManageActivity.start(PrivacyActivity.this, 4, "http://47.107.99.181:8080/imgroup/protocol/protocol.html");
                break;
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 106 :
                    getPersimmions();
                    break;
                case 107 :
                    try {
                        List<BGsetAll> list = BGsetAll.find(BGsetAll.class,"creatid=?",new String[]{ToolsUtils.getMyUserId()});
                        if (null!=list && list.size() > 0){
                            BGsetAll mBGsetAll = list.get(0);
                            mBGsetAll.setBgpath("");
                            mBGsetAll.save();
                        }else {
                            BGsetAll mBGsetAll = new BGsetAll();
                            mBGsetAll.setCreatid(ToolsUtils.getMyUserId());
                            mBGsetAll.setBgpath("");
                            mBGsetAll.save();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    showToast(getResources().getString(R.string.set_finish));
                    break;
            }
        }
    };

    /**
     * 隐私设置的 三个 Switch 监听
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            value = "1";
        } else {
            value = "0";
        }
        switch (buttonView.getId()) {
            case R.id.is_notification:
                newNotification = value;
                if (isChecked){//接收通知
                    new PrefsUtils(App.getInstance(), Constant.NEW_NOTIFICTION).put(Constant.NEW_NOTIFICTION,Constant.NEW_NOTIFICTION_A);
                }else {//不接收通知
                    new PrefsUtils(App.getInstance(),Constant.NEW_NOTIFICTION).put(Constant.NEW_NOTIFICTION,Constant.AGREE_ADD_FRIEND_N);
                }
                updatePrivateSetting();
                break;
            case R.id.is_verify:
                needAuth = value;
                updatePrivateSetting();
                break;
            case R.id.is_find_by_phone:
                searchMobile = value;
                updatePrivateSetting();
                break;
        }
    }

    /**
     * 修改 隐私设置 网络请求
     */
    public void updatePrivateSetting() {

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }

        mPgService.updatePrivateSetting(needAuth, newNotification, searchMobile, userId).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info","ex=="+ex.getDisplayMessage()+ex.getCode());
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity s) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        searchMobile = searchMobile + "";
                        UserEntivity user = ToolsUtils.getUser();
                        if (user != null) {
                            user.setSearchMobile(searchMobile);
                            user.setNeedAuth(needAuth);
                            user.setNewNotification(newNotification);
                            user.save();
                        }
                    }
                }.start();
            }
        });
    }
    /**
     * 做 退出登录 操作
     */
    public void doExit() {
        //App.userEntivity.delete();//从数据库中删除登录信息
        //App.userEntivity = null;//清除之前登陆的数据
        App.isManualLogout = true;
        Intent intent = new Intent(this, LoginActivity.class);
        ToolsUtils.saveLoginstate(this,false,1);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
      //  stopService(new Intent(PrivacyActivity.this,AcceptService.class));
        //先断掉连接，然后关闭socket
        if (App.getInstance().getSocket() != null) {
            App.getInstance().getSocket().disconnect();
            App.getInstance().getSocket().close();
            App.socket=null;
        }
        startActivity(intent);
        finish();


    }

    /**
     * 更新 界面 信息
     */
    private void updateUI() {

        UserEntivity user = ToolsUtils.getUser();
        if (user != null) {
            userId = "" + user.getId();

            searchMobile = user.getSearchMobile();
            needAuth = user.getNeedAuth();
            newNotification = user.getNewNotification();

            isFindByPhone.setChecked(judgeValue(searchMobile));
            isVerify.setChecked(judgeValue(needAuth));
            isNotifaction.setChecked(judgeValue(newNotification));

            isNotifaction.setOnCheckedChangeListener(this);
            isVerify.setOnCheckedChangeListener(this);
            isFindByPhone.setOnCheckedChangeListener(this);
        }
    }

    /**
     * 判断
     * 1 true      0 false
     */
    public boolean judgeValue(String value) {
        return "1".equals(value);
    }


    @TargetApi(23)
    protected void getPersimmions() {
        isgo = false ;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)){
                pos ++ ;
            }
            if (2==pos){
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }else {
            gotoPhoto();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        Log.i(TAG, "getPersimmions: --------002--------");
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            Log.i(TAG, "getPersimmions: --------003--------");
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                Log.i(TAG, "getPersimmions: --------004--------");
                return false;
            } else {
                Log.i(TAG, "getPersimmions: --------005--------");
                permissionsList.add(permission);
                return false;
            }
        } else {
            Log.i(TAG, "getPersimmions: --------0011--------");

            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "getPersimmions: --------006--------");
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Log.i(TAG, "getPersimmions: --------007--------");
                Map<String, Integer> perms = new HashMap<String, Integer>();
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
//                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                Log.i(TAG, "getPersimmions: --------008--------");
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        gotoPhoto();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    boolean isgo = false ;

    private void gotoPhoto(){
        if (!isgo){
            PhotoPickerIntent pt = new PhotoPickerIntent(PrivacyActivity.this);
            pt.setSelectModel(SelectModel.MULTI);
            pt.setShowCarema(true); // 是否显示拍照， 默认false
            pt.setMaxTotal(1); // 最多选择照片数量，默认为9
            //pt.setImageConfig(conFig);
            startActivityForResult(pt,CHOSE_IMG);
        }
        isgo = true ;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHOSE_IMG :
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size()>0){
                        choesimgpath = stringArrayListExtra.get(0);
                        Log.i("info","返回的路径s=="+ choesimgpath);
//                        Bitmap bitmap = PictureUtil.getSmallBitmap(choesimgpath);
                        LookBGImage.startActivity(PrivacyActivity.this,choesimgpath, "", 0);
//                        Bitmap bitmap = BitmapFactory.decodeFile(choesimgpath, new BitmapFactory.Options());
//                        final File file = new File(choesimgpath);
//                        if (file.exists()){
////                            Uri uri = Uri.fromFile(file);
////                            ToolsUtils.cropImageUri(this,uri,600,600,3333);
//                        }else {
//                            ToolsUtils.showToast(PrivacyActivity.this,"所选文件不存在");
//                        }
                    }
                    break;

            }
        }
    }
}
